import tkinter as tk
import random
from tkinter import messagebox

root = tk.Tk()
root.geometry('600x400')
root.title('文本文档水印的嵌入和提取')

wm = tk.StringVar()

tk.Label(root,text = "要嵌入的水印：").grid(row = 0,column=0,pady=5)

wm_entry = tk.Entry(root,textvariable=wm)
wm_entry.grid(row=0,column=1,pady=5)

tk.Label(root,text = "文本：").grid(row=1,column=0)
text_entry = tk.Text(root, height=20, width=50)
text_entry.grid(row=1,column=1,pady=5)

def embed_watermark():
    wm_bin = wm.get()
    text = text_entry.get("1.0", "end")
    if len(wm_bin)*16>len(text):
        messagebox.showinfo("提示", "水印嵌入失败")
    else:
        embed_text = embed(text, wm_bin)
        text_entry.delete('1.0', tk.END)
        text_entry.insert('1.0', embed_text)
        messagebox.showinfo("提示", "水印已成功嵌入")

def extract_watermark():
    text = text_entry.get("1.0", "end")
    extracted_wm = extract(text)
    messagebox.showinfo("提示", "提取的水印为：" + extracted_wm)

def embed(text,wm_binn):
    wm_binn = ' '.join(format(ord(i), 'b') for i in wm_binn)
    len_wm_bin, len_text = len(wm_binn), len(text)

    sentence_embed = ""
    for idx in range(len_text):
        sentence_embed = sentence_embed + text[idx]
        if idx < len(wm_binn):
            if wm_binn[idx] == "1":
                sentence_embed += chr(129)
            if wm_binn[idx] == "0":
                sentence_embed += chr(28)
            if wm_binn[idx] == " ":
                sentence_embed += chr(29)
    return sentence_embed

def extract(text_embed):
    wm_extract_bin = ""
    idx = 0
    while idx < len(text_embed):
        if text_embed[idx] == chr(129):
            wm_extract_bin += '1'
        if text_embed[idx] == chr(28):
            wm_extract_bin += '0'
        if text_embed[idx] == chr(29):
            wm_extract_bin += ' '
        idx += 1
    wm_binnlist = wm_extract_bin.split()
    extract_bin = ""
    i = 0
    while i < len(wm_binnlist):
        extract_bin = extract_bin + chr(int(wm_binnlist[i],2))
        i +=1
    return extract_bin

tk.Button(root,text = "嵌入水印",command=embed_watermark).grid(row=3,column=0,pady=10)
tk.Button(root,text = "提取水印",command=extract_watermark).grid(row=3,column=1,pady=10)

tk.Button(root, text="关闭", command=root.quit).grid(row=3, column=2)

root.mainloop()


# 一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十
# 研究了行移、字移编码的数字文本水印算法利用二值文本的结构特实现了二值文本水印的嵌入和提取。实验结果表明，该算法能够有效的进行水印的嵌入和提取，并具有较强的鲁棒性。

